package service

import (
	"sharePicture/models/dao"
	"sharePicture/models/page"
	"sharePicture/utils"
)

func RegUser(user *dao.User) bool {
	u := dao.User{}
	row := DB.Where("email = ?", user.Email).Find(&u)
	if row.RowsAffected > 0 { //存在不可注册
		return false
	} else {
		row := DB.Select("user_name", "password", "email").Create(user)
		return row.RowsAffected > 0
	}

}

func LoginUser(email string, password string) (dao.User, bool) {
	u := dao.User{}
	row := DB.Where("email=? and password=?", email, password).Find(&u)
	if row.RowsAffected > 0 {
		u.Password = ""
		return u, true
	} else {
		return u, false
	}
}

func GetOwnCollect(uid int, pageNum int, pageSize int) (page.PageInfo, bool) {
	listPicture := []dao.PictureDao{}
	sql := "select * from picture where picture_id in (select picture_id from user_picture where user_id=? and opt=2)"
	row := DB.Raw(sql, uid).Scan(&listPicture)
	pageInfo := utils.SetPageInfo(pageNum, pageSize, row.RowsAffected)
	if row.RowsAffected > 0 {
		newList := []dao.PictureDao{}
		for i := (pageNum - 1) * pageSize; i < int(row.RowsAffected) && i < pageNum*pageSize; i++ {
			newList = append(newList, listPicture[i])
		}
		pageInfo.List = newList
		pageInfo.Size = len(newList)

		return pageInfo, true
	}
	return pageInfo, false
}

func GetOwnUpload(uid int, pageNum int, pageSize int) (page.PageInfo, bool) {

	sql := "select * from picture where user_id=?"
	listPicture := []dao.PictureDao{}
	row := DB.Raw(sql, uid).Scan(&listPicture)
	pageInfo := utils.SetPageInfo(pageNum, pageSize, row.RowsAffected)
	if row.RowsAffected > 0 {
		newList := []dao.PictureDao{}
		for i := (pageNum - 1) * pageSize; i < int(row.RowsAffected) && i < pageNum*pageSize; i++ {
			newList = append(newList, listPicture[i])
		}
		pageInfo.List = newList
		pageInfo.Size = len(newList)
		return pageInfo, true
	}
	return pageInfo, false

}
